<template>
  <div class="app-container">
    <!--地图div-->
    <div class="mapDiv">
      <ThematicMapAnalysisMap
          @getMap="getMap"
          :dataListObj="dataListObj"
          :showLayerArray="showLayerArray"
          :legendInfoArray="legendInfoArray"
      ></ThematicMapAnalysisMap>
    </div>
    <!--index页面div-->
    <div id="thematicMapAnalysisMapDiv" class="ol-popup">
      <!--烈度选择-->
      <div class="map-selectIntensityDiv" v-loading="loading" element-loading-text="正在查询...">
        <el-form :model="queryParams">
          <el-form-item label="烈度：">
            <el-select v-model="queryParams.intensity" @change="onChangeIntensity" placeholder="全部" clearable>
              <el-option v-for="item in intensityDictArray" :key="item.code" :label="item.name"
                         :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <!--表格面板-->
      <Table
             :selectType="selectType"
             :selectId="selectId"
             :selectData="selectData"
             :showTable="detailTable"
             @closeTableDiv="closeDetailResultDiv"
      ></Table>
      <!--数据图层组件-->
      <MapLayers
          :map="map"
          :dataTypeInfoArray="dataTypeInfoArray"
          :layerInfoParams="layerInfoParams"
          :legendInfoHtml="legendInfoHtml"
          :customStylesObj="customStylesObj"
          @getLayerSelectData="getLayerSelectData"
          @setSelectId="setSelectId">
      </MapLayers>
    </div>
  </div>
</template>

<script setup name="thematicMapAnalysis">
//地图
import ThematicMapAnalysisMap from '@/map/disasterVulnerManagement/compreVisualAnalysis/thematicMapAnalysis/map.vue';
//表格面板
import Table from '@/map/disasterDataManagement/maintainData/lifelineSystemInfo/table.vue';
//地图
import MapLayers from '@/map/components/mapLayers/index1.vue';
import { getValidDictItemsByDictCode } from "@/api/map/disasterDataManagement/lifelineSystemInfo.js";
import { specialMapAnalysis } from "@/api/map/disasterVulnerManagement/compreVisualAnalysis/thematicMapAnalysis.js";
import {Fill, Stroke, Style, Icon, Circle as CircleStyle,Text} from 'ol/style';
import { iServerHttp } from "@/map/projMap.js";

const data = reactive({
  queryParams: {
    intensity: "",//烈度
  },
  layerInfoParams: {//查询图层信息参数（图层序号、图层名称、查询条件、是否显示）
    code:"",
    name:"",
    sqlText:'',
    show:false,
    showAllLayers:false,//是否勾选并显示全部图层
  },
});
const {
  queryParams,
  layerInfoParams,
} = toRefs(data);

const loading = ref(false);
const detailTable = ref(false);//是否显示表格面板
//选中查看详情数据
const selectId = ref(null);//选中查看详情数据Id
const selectType = ref("");//选中查看详情数据类型
const selectData = ref([]);//选中查看详情数据Id的1条数据
//查询结果列表
const dataListObj = ref({});
//显示图层列表
const showLayerArray = ref([]);
//数据类型
const dataTypeInfoArray = ref([
  {code:"1",name:"地下管网",table:"czt_dx_pipe_network",url:iServerHttp()+"/iserver/services/map-fxfzczt/rest/maps/czt_dx_pipe_network@fxfzczt",zIndex:10,fieldId:"cdpn_id"},
  // {code:"2",name:"供水-水厂泵房",table:"czt_waterworks",url:iServerHttp()+"/iserver/services/map-fxfzczt/rest/maps/czt_waterworks@fxfzczt",zIndex:5,fieldId:"cw_id"},
  // {code:"3",name:"供水-水厂水池",table:"czt_pool",url:iServerHttp()+"/iserver/services/map-fxfzczt/rest/maps/czt_pool@fxfzczt",zIndex:5,fieldId:"cp_id"},
  // {code:"4",name:"燃气-储气罐",table:"czt_air_receiver",url:iServerHttp()+"/iserver/services/map-fxfzczt/rest/maps/czt_air_receiver@fxfzczt",zIndex:5,fieldId:"car_id"},
  {code:"4",name:"交通-桥梁",table:"czt_bridge_line",url:iServerHttp()+"/iserver/services/map-fxfzczt/rest/maps/czt_bridge_line@fxfzczt",zIndex:5,fieldId:"cb_id"},
  // {code:"6",name:"交通-道路",table:"czt_road",url:iServerHttp()+"/iserver/services/map-fxfzczt/rest/maps/czt_road@fxfzczt",zIndex:4,fieldId:"cr_id"},
  // {code:"7",name:"电力-变电站",table:"czt_transformer_substation",url:iServerHttp()+"/iserver/services/map-fxfzczt/rest/maps/czt_transformer_substation@fxfzczt",zIndex:5,fieldId:"cts_id"},
  // {code:"8",name:"电力-架空线路",table:"czt_overhead_line",url:iServerHttp()+"/iserver/services/map-fxfzczt/rest/maps/czt_overhead_line@fxfzczt",zIndex:4,fieldId:"col_id"},
  // {code:"9",name:"电力-电缆线路",table:"czt_cable_route",url:iServerHttp()+"/iserver/services/map-fxfzczt/rest/maps/czt_cable_route@fxfzczt",zIndex:4,fieldId:"ccr_id"},
  // {code:"10",name:"电力-重要发电厂房",table:"czt_important_powerhouse",url:iServerHttp()+"/iserver/services/map-fxfzczt/rest/maps/czt_important_powerhouse@fxfzczt",zIndex:5,fieldId:"cip_id"},
  // {code:"11",name:"通信-通信室内设备",table:"czt_comm_indoor_equipment",url:iServerHttp()+"/iserver/services/map-fxfzczt/rest/maps/czt_comm_indoor_equipment@fxfzczt",zIndex:5,fieldId:"ccie_id"},
  // {code:"12",name:"通信-电视塔",table:"czt_tv_tower",url:iServerHttp()+"/iserver/services/map-fxfzczt/rest/maps/czt_tv_tower@fxfzczt",zIndex:5,fieldId:"ctt_id"},
]);

//破坏程度图例
const legendInfoHtml = ref("");
const legendInfoArray = ref([
  {fieldProp:"damageExtent",code:"1",label:"基本完好",color:"rgb(255,204,204)",style:null},
  {fieldProp:"damageExtent",code:"2",label:"轻微破坏",color:"rgb(0,153,204)",style:null},
  {fieldProp:"damageExtent",code:"3",label:"中等破坏",color:"rgb(153,204,204)",style:null},
  {fieldProp:"damageExtent",code:"4",label:"严重破坏",color:"rgb(51,204,153)",style:null},
  {fieldProp:"damageExtent",code:"5",label:"倒塌",color:"rgb(255,204,51)",style:null},
]);

//设置破坏程度图例
function setLegendInfoHtml(){
  let html = "";
  let legendArray = legendInfoArray.value;
  for(let i=0;i<legendArray.length;i++){
    let label = legendArray[i].label;
    let color = legendArray[i].color;
    html += '<div style="height: 16px;line-height: 16px;margin-top: 16px;margin-bottom: 16px;">' +
              '<div style="width: 40px;height: 16px;margin-right: 20px;display: inline-block;' +
                'background-color:'+color+';">' +
              '</div>' +
              '<span style="position:relative;top:-2px;line-height: 16px;font-size: 16px;">'+label+'</span>' +
            '</div>';
  }
  legendInfoHtml.value = html;

  //设置图例样式
  for(let i=0;i<legendArray.length;i++){
    let label = legendArray[i].label;
    let color = legendArray[i].color;
    //破坏程度图例样式
    let damageStyle = new Style({
      stroke: new Stroke({
        color: color,
        width: 10,
      }),
      fill: new Fill({
        color: color,
      }),
    });
    legendArray[i].style = damageStyle;
  }
}

//自定义样式
const customStylesObj = ref({});

//设置自定义样式
function setCustomStylesObj(){
  let obj = Object.create(null);
  //选择要素样式
  let selectedStyle = new Style({
    stroke: new Stroke({
      // color: 'rgba(0,131,255,0.8)',
      color: 'rgba(200,20,20,0.8)',
      width: 10,
    }),
    fill: new Fill({
      // color: 'rgba(0,131,255,0.4)',
      color: 'rgba(200,20,20,0.4)',
    }),
  });
  obj["selectedStyle"] = selectedStyle;

  //自定义样式
  let customStyleFunction = function (feature){
    let customStyle = null;
    let queryIntensity = queryParams.value.intensity;
    let legendStyleArray = legendInfoArray.value;
    let allDataListObj = dataListObj.value;
    /*allDataListObj = {
      dxPipeNetwork:{"2010-8":"严重破坏","2000-8":"中等破坏"},
      bridge:{"2010-8":"严重破坏"},
      road:{"0":"严重破坏"}
    }*/
    // console.log("feature.getProperties().attributes");
    // console.log(feature.getProperties().attributes);
    //let layerName = feature.getProperties().layerName || feature.getProperties().layer;
    let layerName="czt_dx_pipe_network@fxfzczt";
    if(layerName=="czt_dx_pipe_network@fxfzczt"){//地下管网
      let dataList1 = allDataListObj.dxPipeNetwork;
      if(dataList1!=undefined && dataList1!=null){
        /*let year = feature.getProperties().attributes["year"];
        let intensity = feature.getProperties().attributes["intensity"];*/

        let year = "1998";
        //let intensity = "8";
        let intensity = queryParams.value.intensity;

        if(queryIntensity==null || queryIntensity=="" || queryIntensity===intensity){
          let key = year + "-" + intensity;
          console.log(key);
          // console.log(layerName+"--key--"+key);
          let damageExtent = dataList1[key];//破坏程度

          if(damageExtent!=undefined && damageExtent!=null){
            for(let j=0;j<legendStyleArray.length;j++){
              if(legendStyleArray[j].label==damageExtent){
                customStyle = legendStyleArray[j].style;
                break;
              }
            }
          }else{
            customStyle = null;
          }
        }
      }
    }else if(layerName=="czt_bridge_line@fxfzczt") {//交通-桥梁
      let dataList2 = allDataListObj.bridge;
      if(dataList2!=undefined && dataList2!=null){
        let year = feature.getProperties().attributes["build_year"];
        let intensity = feature.getProperties().attributes["intensity"];
        if(queryIntensity==null || queryIntensity=="" || queryIntensity===intensity){
          let key = year + "-" + intensity;
          // console.log(layerName+"--key--"+key);
          let damageExtent = dataList2[key];//破坏程度
          if(damageExtent!=undefined && damageExtent!=null){
            for(let j=0;j<legendStyleArray.length;j++){
              if(legendStyleArray[j].label==damageExtent){
                customStyle = legendStyleArray[j].style;
                break;
              }
            }
          }
        }
      }
    }else if(layerName=="czt_road@fxfzczt") {//交通-道路
      let dataList3 = allDataListObj.road;
      if(dataList3!=undefined && dataList3!=null){
        let intensity = feature.getProperties().attributes["fortification"];
        if(queryIntensity==null || queryIntensity=="" || queryIntensity===intensity){
          let key = intensity;
          // console.log(layerName+"--key--"+key);
          let damageExtent = dataList3[key];//破坏程度
          if(damageExtent!=undefined && damageExtent!=null){
            for(let j=0;j<legendStyleArray.length;j++){
              if(legendStyleArray[j].label==damageExtent){
                customStyle = legendStyleArray[j].style;
                break;
              }
            }
          }
        }
      }
    }
    /*let temp = Math.random();
    for(let i=0;i<legendStyleArray.length;i++){
      if(temp<(i+1)*0.2){
        customStyle = legendStyleArray[i].style;
        break;
      }
    }*/
    return customStyle;
  }
  obj["customStyleFunction"] = customStyleFunction();
  customStylesObj.value = obj;
}

//地图传参--start
//地图对象
const map = ref(null);
const getMap = (obj)=>{
  map.value = obj;
  //显示全部图层
  layerInfoParams.value.showAllLayers = true;
}
//地图传参--end

//设防烈度字典数组
const intensityDictArray = ref([]);
//字典表查询--设防烈度
function getValidDictItems(dictCode){
  /*//查询
  getValidDictItemsByDictCode(dictCode).then((response) => {
    nextTick(() => {
      let dictItems = response.data;
      let array = [];
      for(let i=0;i<dictItems.length;i++){
        let obj = {
          code: dictItems[i].dictItemCode,
          name: dictItems[i].dictItemName,
        }
        array.push(obj);
      }
      intensityDictArray.value = array;
    });
  }).catch(err => {
    console.log(err);
  });*/
  //烈度：6-10度
  let array = [];
  let temp = 6;
  for(let i=0;i<5;i++){
    let intensity = (temp + i).toString();
    let obj = {
      code: intensity,
      name: intensity+"度",
    }
    array.push(obj);
  }
  intensityDictArray.value = array;
}

//烈度选择--专题图分析
const onChangeIntensity = ()=>{
  let intensity = queryParams.value.intensity;
  let formData = new FormData();
  //获取数据类型序号
  let type = "";
  let layerArray = showLayerArray.value;
  let dataTypeArray = dataTypeInfoArray.value;
  for(let i=0;i<layerArray.length;i++){
    for(let j=0;j<dataTypeArray.length;j++){
      if(layerArray[i][0]==dataTypeArray[j].name){
        if(type!=""){
          type += ",";
        }
        type += dataTypeArray[j].code;
      }
    }
  }
  if(type!=""){
    formData.append("type", type);
    formData.append("intensity", intensity);
    loading.value = true;
    //专题图分析
    specialMapAnalysis(formData).then((response) => {
      loading.value = false;
      let result = response.data;
      console.log("专题图分析");
      console.log(result);
      dataListObj.value = result;
/*      console.log("dixia----" + result);
      debugger;*/
      //设置自定义样式
      setCustomStylesObj();
    }).catch(err => {
      console.log(err);
      loading.value = false;
    });
  }else{
    dataListObj.value = {};
  }
}

/*//烈度选择--专题图分析
const onChangeIntensity = ()=>{
  //设置自定义样式
  setCustomStylesObj();
}*/

//查询全部图层的全部烈度的专题图分析
const queryAllSpecialMapAnalysis = ()=>{
  let formData = new FormData();
  //获取数据类型序号
  let type = "";
  let dataTypeArray = dataTypeInfoArray.value;
  for(let i=0;i<dataTypeArray.length;i++){
    if(type!=""){
      type += ",";
    }
    type += dataTypeArray[i].code;
  }
  if(type!=""){
    formData.append("type", type);
    formData.append("intensity", "");
    loading.value = true;
    //专题图分析
    specialMapAnalysis(formData).then((response) => {
      loading.value = false;
      let result = response.data;
      console.log("专题图分析");
      console.log(result);
      dataListObj.value = result;
      //设置自定义样式
      setCustomStylesObj();
    }).catch(err => {
      console.log(err);
      loading.value = false;
    });
  }else{
    dataListObj.value = {};
  }
}

//获取勾选的图层数组
const getLayerSelectData = (array)=>{
  // console.log("获取勾选的图层数组");
  // console.log(array);
  showLayerArray.value = array;
  /*if(array && array.length>0){
    //
  }else{
    dataListObj.value = {};
  }*/
}

//设置选择数据ID
const setSelectId = (obj)=>{
  if(obj){
    selectData.value = [obj];
    let id = obj.selectId;
    let dataType = obj.selectType;
    handleDetil(id,dataType);
  }
}

//根据id查询数据
function handleDetil(id,dataType){
  detailTable.value = false;//关闭表格面板
  nextTick(() => {
    selectId.value = id;//选中查看详情数据Id
    selectType.value = dataType;//选中查看详情数据类型
    detailTable.value = true;//打开表格面板
  });
}

//关闭表格面板
function closeDetailResultDiv(){
  detailTable.value = false;//关闭表格面板
}

onMounted(() => {
  //查询设防烈度字典表
  getValidDictItems("smxsfld");
  //设置破坏程度图例
  setLegendInfoHtml();
  //设置自定义样式
  // setCustomStylesObj();
  //查询全部图层的全部烈度的专题图分析
  queryAllSpecialMapAnalysis();
})
</script>

<style lang="scss" scoped>
.mapDiv {
  position:absolute;top:0px;left:0px;width:100%;height:100%;
}
.map-selectIntensityDiv {
  position:absolute;
  top:16px;
  left:110px;
  width:200px;
  height:100px;
  box-shadow: 0px 0px 20px #414d74;
  border:2px solid #e5ebf7;
  border-radius:8px;
  background:#ffffff;
  padding:20px;
  padding-top: 30px;
  z-index:1;
}

.map-legendDiv {
  position: relative;
  height: 16px;
  line-height: 16px;
  font-size: 13px;
  margin: 8px;
}
.map-legendDiv span {
  line-height: 16px;
  font-size: 13px;
}
.map-legendDiv div {
  position: relative;
  top: 2px;
  left: 8px;
  width: 30px;
  height: 14px;
  margin: 0px !important;
  margin-right: 25px !important;
  display: inline-block;
}
.map-legendDiv div div {
  position: relative !important;
  left: 0px !important;
  top: 0px !important;
  border:1px solid black;
  background:#fff;
}
</style>